<?php
class ArticleModel {
    private $article_db;
    
    public function __construct() {
        $this->article_db = new ArticleDb();
    }

    private function getArticleNumber($book_id) {
        $where = array(
            'book_id' => $book_id,
        );
        $column = array('number');
        $order_by = 'number desc';
        $r = $this->article_db->selectRow($where, $column,0, '', $order_by);
        if(empty($r)) {
            return 1;
        }
        return $r['number'] + 1;
    }

    public function add($data) {
        $data['create_time'] = time();
        $data['book_id'] = BookModel::decryptSid($data['book_sid']);
        $data['number'] = $this->getArticleNumber($data['book_id']);
        $data['content'] = str_replace("\r\n", "\n", $data['content']);
        $data['content'] = str_replace("\r", "\n", $data['content']);
//        $data['content'] = str_replace("\n\n", "\n", $data['content']); //删除空行
        $data['content'] = rtrim($data['content']); //删除结尾换行
        $data['content'] = ltrim($data['content'], "\0\n\t");
        $data['content'] = preg_replace('/\n{2,}/', "\n", $data['content']);//多于两个的换行转成1个换行
        $data['content'] = preg_replace('/ {2,}/','  ', $data['content']); //多于2个的空格转成2个空格
        $data['length'] = mb_strlen($data['content'], 'utf-8');
        $this->article_db->insertRow($data);
        $article_file = new ArticleFile();
        return $article_file->set($data);
    }

    public function getArticles($book_sid) {
        $where = array(
            'book_id' => BookModel::decryptSid($book_sid),
        );
        $column = array('number', 'name', 'length');
        $order_by = 'number asc';
        $r = $this->article_db->selectRows($where, $column, 0, '', '', $order_by);
        $tmp = array();
        foreach($r as $one) {
            $tmp[$one['number']] = $one;
        }
        return $r;
    }

    public function getByNumber($book_sid, $number) {
        $where = array(
            'book_id' => BookModel::decryptSid($book_sid),
            'number' => $number,
        );
        return $this->article_db->selectRow($where);
    }

    public function update($book_sid, $number, $data) {
        $where = array(
            'book_id' => BookModel::decryptSid($book_sid),
            'number' => $number,
        );
        $this->article_db->update($where, $data);
        $article_file = new ArticleFile();
        $data['book_sid'] = $book_sid;
        $data['number'] = $number;
        return $article_file->set($data);
    }
}
?>
